import pygame
from pygame.locals import *


class Kun(pygame.sprite.Sprite):
    def __init__(self, target, health=120, speed=0.3, filename='resources/images/kun.png'):
        pygame.sprite.Sprite.__init__(self)
        self.image = None
        self.frame = 0
        self.old_frame = -1
        self.frame_width = 1
        self.frame_height = 1
        self.first_frame = 0
        self.last_frame = 0
        self.columns = 1
        self.last_time = 0
        self.health = health
        self.speed = speed

    # 　　使用property方法，让精灵类对坐标操作更方便
    def _getx(self):
        return self.rect.x

    def _setx(self, value):
        self.rect.x = value

    X = property(_getx, _setx)

    def _gety(self):
        return self.rect.y

    def _sety(self, value):
        self.rect.y = value

    Y = property(_gety, _sety)

    def _getpos(self):
        return self.rect.topleft

    def _setpos(self, pos):
        self.rect.topleft = pos

    position = property(_getpos, _setpos)

# load方法中定义了图片位置，长宽和帧的列数，由此来将素材切成一帧一帧
    def load(self, filename, width=285, height=101, columns=3):
        self.image = pygame.image.load(filename).convert_alpha()
        self.frame_width = width
        self.frame_height = height


        # 这里参数可能需要改
        self.rect = Rect(900, 150, width, height)
        self.columns = columns
        rect = self.image.get_rect()
        self.last_frame = (rect.width // width) * (rect.height // height) - 1

    def update(self, current_time, rate=30):
        # 　　更新帧数
        if current_time > self.last_time + rate:
            self.frame += 1
            if self.frame > self.last_frame:
                self.frame = self.first_frame
            self.last_time = current_time

        # 当帧数发生改变时，创建新的图片
        if self.frame != self.old_frame:
            frame_x = (self.frame % self.columns) * self.frame_width
            frame_y = (self.frame // self.columns) * self.frame_height
            rect = Rect(frame_x, frame_y, self.frame_width, self.frame_height)
            self.image = self.image.subsurface(rect)
            self.old_frame = self.frame

    def move(self):
        self.X -= self.speed
